from plugin import PlugIn
import random
import sys

try:
	from plugin_conf import * 
except:
	print "Can't read the configure file: plugin_conf.py"
	print "maybe you must copy plugin_conf.py.default to plugin_conf.py"
	sys.exit(1)


class Cmd_Plugin(PlugIn):
    def __init__(self):
        PlugIn.__init__(self)
        DBG_LINE='command'
        self._exported_methods=[]
        for i in dir(self):
            if i[-7:]=='Handler' and i[:-7].lower()==i[:-7]: 
                self._exported_methods.append(getattr(self,i))
    def plugin(self, owner):
        """ Plug the Dispatcher instance into Client class instance and send initial stream header. Used internally."""
        return owner.init_command()

    def plugout(self):
        """ Prepares instance to be destructed. """
        return self._owner.init_command()


class Cmd_Roll(Cmd_Plugin):
    def __init__(self):
        Cmd_Plugin.__init__(self)

    def rollHandler(self, who, msg):
        '"/roll" roll (1-100).'
        self._owner.systoall("%s roll %d"%(self._owner.getdisplayname(who, is_sign=True), random.randint(1,100)))

class Cmd_Me(Cmd_Plugin):
    def __init__(self):
		Cmd_Plugin.__init__(self)
		
    def meHandler(self, who, msg):
        '"/me <emote> [<msg>]" Says an emote as you'
		#print 'Emotion called: %s' % msg
        if msg.strip()=="":
            action=random.choice(emote_conf['emotes'].keys())
            self._owner.systoone(who, ('Usage: /me <emote>\r\nSays an emote as you.  eg "/me %(action)s <msg>" shows as "%(nick)s %(emote)s <msg>" to everyone else') % ({
                "nick" : self._owner.getdisplayname(who),
                "action" : action,
                "emote" : emote_conf['emotes'][action]}))
        else:
	    msg = msg.lstrip()
            if " " in msg:
                action, msg = msg.split(" ", 1)
            else:
                action, msg = msg, " "
            emote = emote_conf['emotes'].get(action, "")
            if emote:
                emote = "_%s_" % emote
            self._owner.sendtoall(('<%s> %s %s') % (self._owner.getdisplayname(who, is_sign=True),emote,msg),butnot=[self._owner.getdisplayname(who).lower()])
            self._owner.systoone(who, ('You %s %s') % (emote, msg))

    def emotesHandler(self, who, msg):
        '"/emotes" list the emotes can be used in "/me" command.'
        self._owner.systoone(who, "the emotes can be used:\n%s"%
            "\n".join(["%-20s%s"%(x,y) for x,y in emote_conf['emotes'].items()]))

class Cmd_Sign(Cmd_Plugin):
    def __init__(self):
        Cmd_Plugin.__init__(self)
        self._escapeChars = '|:="[]()*#<>\\+-'
    
    def escapeChar(self, c):
        if c in self._escapeChars:
            return ''
        else:
            return c

    def signHandler(self, who, msg):
    	'''"/sign [Your signature]" Make your own signature/nickname'''
        user = self._owner.getdisplayname(who).lower()
        sign = self.cleanFilter(msg)
        
        if sign == '':
            sign = self._owner.sign_map.get(user, '')
            self._owner.systoone(who, 'Your signature: %s' % sign)
            return 
        
        if len(msg) > 50:
            self._owner.systoone(who, 'Make it shorter, bunny')
            return
        else:
            self._owner.sign_map[user] = sign
            self._owner.systoone(who, 'Your signature: %s' % sign)
    
    def renameHandler(self, who, msg):
        '''
            /rename user signature
        '''
        user = self._owner.getindexname(who)
        if CONST_ADMIN == admin_conf.get(user, 0):
            temp = msg.split()
            if len(temp) > 1:
                target = temp[0]
                sign = temp[1]
                if target in self._owner.user_list:
                    self._owner.sign_map[target] = sign
                    self._owner.systoone(who, '''Rename signature of %s to %s\n''' % (target, sign))
                else:
                    self._owner.systoone(who, '''No such user %s in this room''' % target)
            else:
                self._owner.systoone(who, '''Please input "/rename target signature"\n''')
        else:
                self._owner.systoone(who, '''No permission to this command''')
    
    def cleanFilter(self, user_input):
        'All inputs are evil'
        return ''.join([self.escapeChar(c) for c in user_input])
